package cn.edu.pzhu.javaweb.controller;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.pzhu.javaweb.pojo.User;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		if(username==null || password==null || username.isEmpty() || password.isEmpty()) {
			response.getWriter().print("<script>alert('用户名或密码不能为空!');location.href='login.jsp';</script>");
			return;	
		}
		
		ServletContext application = request.getServletContext();
		Object object = application.getAttribute(username+"_user");
		if (object==null) {
			response.getWriter().print("<script>alert('此用户不存在，请先注册!');location.href='login.jsp';</script>");
			return;	
		}
		if(object instanceof User ) {
			User user = (User)object;
			if(!user.getPassword().equals(password)) {
				response.getWriter().print("<script>alert('密码错误!');location.href='login.jsp';</script>");
				return;
			}else {
				request.getSession().setAttribute("username", username);//存储登录人的名字，如果有这个名字就表示登录了
				
				response.getWriter().print("<script>alert('登录成功!');location.href='index.jsp';</script>");
				return;
			}
		}
		
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
